package com.ynet.middleground.user.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ynet.cache.redis.IfpRedisson;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.approve.bean.QueryRunningProcessReq;
import com.ynet.middleground.approve.service.ProcessInstanceService;
import com.ynet.middleground.contract.bean.GetOssUrlReq;
import com.ynet.middleground.contract.service.OssService;
import com.ynet.middleground.user.bean.*;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.*;
import com.ynet.middleground.user.entity.*;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 通用服务类，不存放静态方法
 * @Param:
 * @return:
 * @Author: DaiGaoLe
 * @Date:
 */

@Component
public class GeneralService {

    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    ProcessInstanceService processInstanceService;

    @Reference(version = "0.0.1", check = false, protocol = "dubbo")
    OssService ossService;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    private UserBaseInformationMapper userBaseInformationMapper;


    @Autowired
    UserBaseInformationHistoryMapper userBaseInformationHistoryMapper;

    @Autowired
    EnterpriseUserInfoHistoryMapper enterpriseUserInfoHistoryMapper;

    @Autowired
    NaturalPersonBaseInformationHistoryMapper naturalPersonBaseInformationHistoryMapper;

    @Autowired
    EnterpriseBasicInfoHistoryMapper enterpriseBasicInfoHistoryMapper;

    @Autowired
    EnterpriseUserInfoMapper enterpriseUserInfoMapper;

    @Autowired
    NaturalPersonBaseInformationMapper naturalPersonBaseInformationMapper;

    @Autowired
    EnterpriseBasicInfoMapper enterpriseBasicInfoMapper;


    /**
     * @Description: 根据用户id获取审批中    心是否存在途任务
     * @Param:
     * @return:
     * @Author: DaiGaoLe
     * @Date:
     */
    public boolean isJoinUnfinishedProcess(Integer userId, BaseReqObj obj) {
        // 声明变量 begin
        Boolean result = false;
        // 声明变量 end
        // 请求审批中心的请求对象
        QueryRunningProcessReq requestObject = dozerBeanMapper.map(obj, QueryRunningProcessReq.class);
        requestObject.setStartUserId(userId.toString());
        // 审批中心的返回结果 有在途任务的话返回时true,没有在途任务的话返回时false
        PagerInfo pagerInfo = new PagerInfo();
        pagerInfo.setPageNum(1);
        pagerInfo.setPageSize(1);
        pagerInfo.setTotal(1);
        requestObject.setPagerInfo(pagerInfo);
        ServiceResult<Boolean> joinUnfinishedProcess = processInstanceService.isJoinUnfinishedProcess(requestObject);
        result = joinUnfinishedProcess.getResult();

        // 判断审批中心是否调用正常，如果不正常的告诉渠道错我提示
        if (result == null) {
            throw new BusinessException(joinUnfinishedProcess.getErrorMsg(), joinUnfinishedProcess.getErrorCode());
        }
        return result;
    }


    /**
     * @Description: 根据用户id 判断用户是否存在，存在返回true，不存在返回false
     * @Param:
     * @return:
     * @Author: DaiGaoLe
     * @Date:
     */
    public boolean isUserExist(Integer userId) {
        UserBaseInformation userBaseInformation = userBaseInformationMapper.selectById(userId);
        if (userBaseInformation != null) {
            return true;
        }
        return false;
    }


    /**
     * @Description: 根据用户id 判断用户是否存在，提示用户信息
     * @Param:
     * @return:
     * @Author: DaiGaoLe
     * @Date:
     */
    public void isUserExistPrompt(Integer userId) {
        List<String> userType = new ArrayList<String>();
        userType.add(SystemConstant.USER_TYPE_5);
        LambdaQueryWrapper<UserBaseInformation> queryWrapper = new LambdaQueryWrapper<UserBaseInformation>();
        queryWrapper.eq(UserBaseInformation::getUserId, userId);
        queryWrapper.notIn(UserBaseInformation::getUserType, userType);
        UserBaseInformation userBaseInformation = userBaseInformationMapper.selectOne(queryWrapper);
        if (userBaseInformation == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0002_MESSAGE,ErrorMessageConstant.ECUC0002_CODE);
        }
    }

    public Integer insertUserBaseInformationHistory(UserBaseInformation userBaseInformation) {
        UserBaseInformationHistory userBaseInformationHistory = dozerBeanMapper.map(userBaseInformation, UserBaseInformationHistory.class);
        userBaseInformationHistoryMapper.insert(userBaseInformationHistory);
        return userBaseInformationHistory.getId();
    }

    public void insertEnterpriseUserInfoHistory(EnterpriseUserInfo enterpriseUserInfo, Integer userHistoryId) {
        EnterpriseUserInfoHistory enterpriseUserInfoHistory = dozerBeanMapper.map(enterpriseUserInfo, EnterpriseUserInfoHistory.class);
        enterpriseUserInfoHistory.setId(userHistoryId);
        enterpriseUserInfoHistoryMapper.insert(enterpriseUserInfoHistory);
    }

    public void insertNaturalPersonBaseInformationHistory(NaturalPersonBaseInformation naturalPersonBaseInformation, Integer userHistoryId) {
        NaturalPersonBaseInformationHistory naturalPersonBaseInformationHistory = dozerBeanMapper.map(naturalPersonBaseInformation, NaturalPersonBaseInformationHistory.class);
        naturalPersonBaseInformationHistory.setId(userHistoryId);
        naturalPersonBaseInformationHistoryMapper.insert(naturalPersonBaseInformationHistory);
    }

    public void insertEnterpriseBasicInfoHistory(EnterpriseBasicInfo enterpriseBasicInfo, Integer userHistoryId) {
        EnterpriseBasicInfoHistory enterpriseBasicInfoHistory = dozerBeanMapper.map(enterpriseBasicInfo, EnterpriseBasicInfoHistory.class);
        enterpriseBasicInfoHistory.setId(userHistoryId);
        enterpriseBasicInfoHistoryMapper.insert(enterpriseBasicInfoHistory);
    }

    @Autowired
    EmployeeInformationHistoryMapper employeeInformationHistoryMapper;

    public void insertEmployeeInformationHistory(EmployeeInformation employeeInformation, Integer userHistoryId) {
        EmployeeInformationHistory employeeInformationHistory = dozerBeanMapper.map(employeeInformation, EmployeeInformationHistory.class);
        employeeInformationHistory.setId(userHistoryId);
        employeeInformationHistoryMapper.insert(employeeInformationHistory);
    }



    public void updateEnterpriseUserInfo(ChangeUserInfoReq requestObject,ChangeUserInfoEnterpriseUserInfo changeUserInfoEnterpriseUserInfo, EnterpriseUserInfo enterpriseUserInfo, Integer operationUserId) {
//        dozerBeanMapper.map(changeUserInfoEnterpriseUserInfo, enterpriseUserInfo);
        if(requestObject!=null) {
            dozerBeanMapper.map(requestObject,enterpriseUserInfo);
        }
        if(changeUserInfoEnterpriseUserInfo!=null) {
            enterpriseUserInfo.setEmail(changeUserInfoEnterpriseUserInfo.getEmail());
            enterpriseUserInfo.setDescribeStr(changeUserInfoEnterpriseUserInfo.getDescribeStr());
            enterpriseUserInfo.setAdminLicenseUrl(changeUserInfoEnterpriseUserInfo.getAdminLicenseUrl());
        }
        enterpriseUserInfo.setGmtModified(LocalDateTime.now());
        enterpriseUserInfo.setModifiedBy(operationUserId);
        LambdaQueryWrapper<EnterpriseUserInfo> queryWrapperEUI = new LambdaQueryWrapper<EnterpriseUserInfo>();
        queryWrapperEUI.eq(EnterpriseUserInfo::getUserId, enterpriseUserInfo.getUserId());
        queryWrapperEUI.eq(EnterpriseUserInfo::getEntOperatorId, requestObject.getEnterpriseId());
        queryWrapperEUI.eq(EnterpriseUserInfo::getChannel, requestObject.getChannel());
        queryWrapperEUI.eq(EnterpriseUserInfo::getIsDelete, SystemConstant.IS_DELETE_0);
        enterpriseUserInfoMapper.update(enterpriseUserInfo, queryWrapperEUI);
    }

    public void updateNaturalPersonBaseInformation(ChangeUserInfoReq requestObject,ChangeUserInfoNaturalPersonBase changeUserInfoNaturalPersonBase, NaturalPersonBaseInformation naturalPersonBaseInformation, Integer operationUserId) {
        if(changeUserInfoNaturalPersonBase != null) {
            dozerBeanMapper.map(changeUserInfoNaturalPersonBase, naturalPersonBaseInformation);
        }
        //        dozerBeanMapper.map(requestObject, naturalPersonBaseInformation);
        if(requestObject!=null) {
            naturalPersonBaseInformation.setTelephone(requestObject.getTelephone());
            naturalPersonBaseInformation.setUserName(requestObject.getUserName());
            naturalPersonBaseInformation.setPapersType(requestObject.getPapersType());
            naturalPersonBaseInformation.setPapersNo(requestObject.getPapersNo());
            naturalPersonBaseInformation.setUserAddress(requestObject.getUserAddress());
            naturalPersonBaseInformation.setGmtModified(LocalDateTime.now());
            naturalPersonBaseInformation.setModifiedBy(operationUserId);
        }
        LambdaQueryWrapper<NaturalPersonBaseInformation> queryWrapperNPB = new LambdaQueryWrapper<NaturalPersonBaseInformation>();
        queryWrapperNPB.eq(NaturalPersonBaseInformation::getUserId, requestObject.getUserId());
        naturalPersonBaseInformationMapper.update(naturalPersonBaseInformation, queryWrapperNPB);
    }

    public void updateEnterpriseBasicInfo(ChangeUserInfoEnterpriseBasicInfo changeUserInfoEnterpriseBasicInfo,EnterpriseBasicInfo enterpriseBasicInfo,Integer operationUserId) {
        changeUserInfoEnterpriseBasicInfo.setChannel(enterpriseBasicInfo.getChannel());
        dozerBeanMapper.map(changeUserInfoEnterpriseBasicInfo, enterpriseBasicInfo);
        enterpriseBasicInfo.setGmtModified(LocalDateTime.now());
        enterpriseBasicInfo.setModifiedBy(operationUserId);
        LambdaQueryWrapper<EnterpriseBasicInfo> queryWrapperEBI = new LambdaQueryWrapper<EnterpriseBasicInfo>();
        queryWrapperEBI.eq(EnterpriseBasicInfo::getUserId, enterpriseBasicInfo.getUserId());
        enterpriseBasicInfoMapper.update(enterpriseBasicInfo, queryWrapperEBI);
    }

    // add by gaole.dai 2020-01-02 抽出用户不存在闸口 begin
    public UserBaseInformation whetherTheUserHasAGate(Integer userId){
        if (userId == null) {
            throw new BusinessException("用户id不能为空", ErrorMessageConstant.ECUC0001_CODE);
        }
        UserBaseInformation userBaseInformation = userBaseInformationMapper.selectById(userId);
        if (userBaseInformation == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0002_MESSAGE, ErrorMessageConstant.ECUC0001_CODE);
        }
        return userBaseInformation;
    }
    // add by gaole.dai 2020-01-02 抽出用户不存在闸口 end

    // add by gaole.dai 2020-01-02 抽出手机号是否符合规则的闸口 end
    public void whetherTheTelephoneNumberConformsToTheRules(String telephone){
        if (StringUtils.isEmpty(telephone)) {
            throw new BusinessException("手机号不能为空", ErrorMessageConstant.ECUC0001_CODE);
        }
        if (!CommUtils.isPhone(telephone)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0019_MESSAGE, ErrorMessageConstant.ECUC0019_CODE);
        }
    }
    // add by gaole.dai 2020-01-02 抽出手机号是否符合规则的闸口 end


    // add by gaole.dai 2020-01-02 抽出邀请制闸口 begin
    @Autowired
    private SystemParametersMapper systemParametersMapper;

    @Autowired
    InviteeInformationMapper inviteeInformationMapper;

    @Autowired
    private IfpRedisson redisson;

    // 抽出邀请制闸口
    public void  invitationGate(String channel,String userName,String contacts,String telephone,String inviteCode,String oppositePapersNo,String userType) {
        // 手机号校验
        whetherTheTelephoneNumberConformsToTheRules(telephone);


        if (StringUtils.isEmpty(channel)) {
            throw new BusinessException("渠道不能为空", ErrorMessageConstant.ECUC0001_CODE);
        }

        if (StringUtils.isEmpty(contacts)) {
            throw new BusinessException("联系人不能空", ErrorMessageConstant.ECUC0001_CODE);
        }

//        if (StringUtils.isEmpty(userName)) {
//            throw new BusinessException("被邀请人不能为空", ErrorMessageConstant.ECUC0001_CODE);
//        }

        if (StringUtils.isEmpty(inviteCode)) {
            throw new BusinessException("邀请码不能为空", ErrorMessageConstant.ECUC0001_CODE);
        }
        //2021-06-30 补录增加可补录自然人
        String id = "";
        if(SystemConstant.USER_TYPE_2.equals(userType)){
            if(StringUtils.isBlank(oppositePapersNo)){
                throw new BusinessException(ErrorMessageConstant.ECUC0062_MESSAGE, ErrorMessageConstant.ECUC0062_CODE);
            }
            id = oppositePapersNo + contacts + telephone;
        }else{
            if(StringUtils.isBlank(userName)){
                throw new BusinessException(ErrorMessageConstant.ECUC0063_MESSAGE, ErrorMessageConstant.ECUC0063_CODE);
            }
            id = userName + contacts + telephone;
        }
//        QueryWrapper<SystemParameters> queryWrapperSp0 = new QueryWrapper<>();
//        queryWrapperSp0.eq(SystemConstant.SYSTEM_PARAMETERS_CODE, SystemConstant.SYSTEM_PARAMETERS_CODE_0000000004);
//        queryWrapperSp0.eq(SystemConstant.SYSTEM_PARAMETERS_NAME, SystemConstant.SYSTEM_PARAMETERS_NAME_0000000004);
//        List<SystemParameters> systemParameters0 = systemParametersMapper.selectList(queryWrapperSp0);
//
//        if (systemParameters0 == null || systemParameters0.size() == 0) {
//            throw new BusinessException("系统参数没有配置", ErrorMessageConstant.ECUC0000_CODE);
//        }
//
//        if (systemParameters0.size() > 1) {
//            throw new BusinessException("系统参数配置异常", ErrorMessageConstant.ECUC0000_CODE);
//        }

//        SystemParameters systemParameter0 = systemParameters0.get(0);
//         if (systemParameter0.getValue().contains(channel)) {
            // 此处的id没有加上邀请人的用户id
//            String id =
//                    userName + contacts + telephone;
            QueryWrapper<InviteeInformation> queryWrapperIi = new QueryWrapper<>();
            //queryWrapperIi.eq("user_id", userId);
            if(SystemConstant.USER_TYPE_2.equals(userType)){
                queryWrapperIi.eq("papers_no", oppositePapersNo);
                queryWrapperIi.eq("user_type", SystemConstant.USER_TYPE_2);
            }else{
                queryWrapperIi.eq("enterprise_name", userName);
                queryWrapperIi.eq("user_type", SystemConstant.USER_TYPE_0);
            }
            queryWrapperIi.eq("contacts", contacts);
            queryWrapperIi.eq("contacts_telephone", telephone);
            // 状态必须是0的
            queryWrapperIi.eq("state", "0");
            // 在有效期内
            queryWrapperIi.ge("end_time",LocalDateTime.now());
            List<InviteeInformation> inviteeInformations = inviteeInformationMapper.selectList(queryWrapperIi);

            if (inviteeInformations.size() == 0) {
                throw new BusinessException(ErrorMessageConstant.ECUC0041_MESSAGE, ErrorMessageConstant.ECUC0041_CODE);
            }

            if (inviteeInformations != null && inviteeInformations.size() > 0) {
                if (StringUtils.isEmpty(inviteCode)) {
                    throw new BusinessException("当前注册用户已被邀请，邀请码不能为空", ErrorMessageConstant.ECUC0001_CODE);
                }
                //2020-11-19聚信要求删除渠道限制
//                queryWrapperIi.eq("channel", channel);
//                Integer isItTheChannel = inviteeInformationMapper.selectCount(queryWrapperIi);
//                if (isItTheChannel == null || isItTheChannel == 0) {
//                    throw new BusinessException(ErrorMessageConstant.ECUC0042_MESSAGE, ErrorMessageConstant.ECUC0042_CODE);
//                }
//修改验证方式 宋一帆 2020-08-04
//                QueryWrapper<UserBaseInformation> queryWrapperUbi = new QueryWrapper<>();
//                queryWrapperUbi.eq("invite_code", inviteCode);
//
//                List<UserBaseInformation> userBaseInformations = userBaseInformationMapper.selectList(queryWrapperUbi);
//                if (userBaseInformations == null || userBaseInformations.size() == 0) {
//                    throw new BusinessException("邀请码不一致", ErrorMessageConstant.ECUC0011_CODE);
//                }
//                id = id + userBaseInformations.get(0).getUserId();
                queryWrapperIi.eq("invite_code", inviteCode);
                Integer isTheChannel = inviteeInformationMapper.selectCount(queryWrapperIi);
                if (isTheChannel == null || isTheChannel == 0) {
                    throw new BusinessException("邀请码不一致", ErrorMessageConstant.ECUC0011_CODE);
                }

                //Add By Liwq On 2020-11-25 Start
                //跨渠道邀请注册，要校验本次传参channel，是否属于 邀请信息表.可用渠道 字段里面。
                if (isTheChannel != null || isTheChannel > 0) {
                    InviteeInformation tempInviteInfo = inviteeInformationMapper.selectList(queryWrapperIi).get(0);
                    //可用渠道为空，便给报错，当前注册用户没有在当前系统被邀请。
                    if(StringUtils.isEmpty(tempInviteInfo.getAvailableChannel())){
                        throw new BusinessException(ErrorMessageConstant.ECUC0051_MESSAGE, ErrorMessageConstant.ECUC0051_CODE);
                    }
                    //可用渠道不为空，但是当前渠道不属于可用渠道的话，也给报错。
                    if(tempInviteInfo.getAvailableChannel().indexOf(channel) == -1){
                        throw new BusinessException(ErrorMessageConstant.ECUC0051_MESSAGE, ErrorMessageConstant.ECUC0051_CODE);
                    }
                }
                //Add By Liwq On 2020-11-25 End

                Integer userId = inviteeInformationMapper.selectOne(queryWrapperIi).getUserId();
                id = id + userId;
                String redisKey = CommUtils.getRedisKey("uubi", "inviteCode", id);
                String key = redisson.get(redisKey);
                if (StringUtils.isEmpty(key)) {
                    throw new BusinessException(ErrorMessageConstant.ECUC0043_MESSAGE, ErrorMessageConstant.ECUC0043_CODE);
                }
            }
//        }
    }
    // add by gaole.dai 2020-01-02 抽出邀请制闸口 end

    // add by gaole.dai 2020-01-02 抽出判断是否是邀请制闸口 end
    public boolean determineIfItIsAnInvitationSystem(String channel){
        if (StringUtils.isEmpty(channel)) {
            throw new BusinessException("渠道参数不能为空", ErrorMessageConstant.ECUC0001_CODE);
        }
        QueryWrapper<SystemParameters> queryWrapperSp0 = new QueryWrapper<>();
        queryWrapperSp0.eq(SystemConstant.SYSTEM_PARAMETERS_CODE, SystemConstant.SYSTEM_PARAMETERS_CODE_0000000004);
        queryWrapperSp0.eq(SystemConstant.SYSTEM_PARAMETERS_NAME, SystemConstant.SYSTEM_PARAMETERS_NAME_0000000004);
        List<SystemParameters> systemParameters0 = systemParametersMapper.selectList(queryWrapperSp0);

        if (systemParameters0 == null || systemParameters0.size() == 0) {
            throw new BusinessException("系统参数没有配置", ErrorMessageConstant.ECUC0000_CODE);
        }

        if (systemParameters0.size() > 1) {
            throw new BusinessException("系统参数配置异常", ErrorMessageConstant.ECUC0000_CODE);
        }

        SystemParameters systemParameter0 = systemParameters0.get(0);
        if (systemParameter0.getValue().contains(channel)) {
            return true;
        }else{
            return false;
        }
    }
    // add by gaole.dai 2020-01-02 抽出判断是否是邀请制闸口 end

    public String getOssUrl(BaseReqObj requestObject,String shortUrl){
        GetOssUrlReq req = dozerBeanMapper.map(requestObject, GetOssUrlReq.class);
        req.setShortUrl(shortUrl);
        return ossService.getOssFullUrl(req).getResult().getFullUrl();
    }
}
